import re

from aestate.ajson import aj
from django.http import StreamingHttpResponse
from django.shortcuts import render, redirect
from rest_framework.views import APIView

from apps.base_data.models import User
from utils import MD5
from utils.network import Result, CustomGenericViewSet
from utils import FileUtil, ModelUtil
import numpy as np


class DownloadView(CustomGenericViewSet):
    def get(self, request):
        cookies = request.COOKIES
        user = ModelUtil.get_user(aj.load(cookies['user'])['email'])
        fstream = FileUtil.get_file_stream(
            user.email, request.GET.get('filename'))
        response = StreamingHttpResponse(fstream)
        response['Content-Type'] = 'application/txt'
        # 注意filename 这个是下载后的名字
        response['Content-Disposition'] = 'attachment;filename="{}"'.format(
            request.GET.get('filename'))
        return response

    def motify(self, request):
        cookies = request.COOKIES
        email = aj.load(cookies['user'])['email']
        filename = request.GET.get('filename')
        user = ModelUtil.get_user(email)
        csv = ModelUtil.read_csv(email, filename)
        head = csv.columns.tolist()
        csv = csv.where(csv.notnull(), '_')
        data = np.array(csv)
        print(data)
        if 'json' in request.GET.keys():
            return Result.success(data={
                'filename': filename,
                'head': head,
                'data': data
            })
        else:
            req = render(request, 'tables.html', {
                'filename': filename,
                'head': head,
                'data': data
            })
            req.set_cookie('user', user.to_json())
            return req

    def update(self, request):
        cookies = request.COOKIES
        email = aj.load(cookies['user'])['email']
        user = ModelUtil.get_user(email)
        data = request.data
        filename = data.get('filename')
        head = aj.load(data.get('head'))
        columns = aj.load(data.get('columns'))
        new_data = [head, *columns]
        FileUtil.write_file(user.email, filename, new_data)
        return Result.success(data={
            'filename': filename,
            'head': head,
            'data': columns,
            'status': 'Success'
        })


class JoinView(APIView):
    def get(self, request):
        return render(request, 'join.html')

    def post(self, request):
        data = request.data
        email = data['email']
        if not re.match(r'^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\.[com,cn,net]{1,3}$', email):
            return render(request, 'join.html', {'error_text': '邮箱不正确'})
        password = data['password']
        if len(password) < 6:
            return render(request, 'join.html', {'error_text': '密码长度太小了，请输入6位以上'})
        hasUser = User().orm.find().where(email=email).end()
        if len(hasUser) > 0:
            return render(request, 'join.html', {'error_text': '邮箱已经被注册'})
        user = User(email=email, password=MD5.de(password))
        user.save()
        FileUtil.create_dir(user.email)
        req = render(request, 'join.html', {'login': True})
        req.set_cookie('user', user.to_json())
        return req


class LoginView(APIView):
    def get(self, request):
        cookies = request.COOKIES
        if 'user' in cookies.keys():
            return redirect('/dashboard')
        return render(request, 'login.html')

    def post(self, request):
        data = request.data
        user = ModelUtil.get_user(data['email'])
        if user is None:
            return render(request, 'login.html', {'error_text': 'User does not exist'})
        if user.password == MD5.de(data['password']):
            req = render(request, 'login.html', {'login': True})
            req.set_cookie('user', user.to_json())
            return req
        return render(request, 'login.html', {'error_text': 'Wrong password'})


class IndexView(CustomGenericViewSet):
    def get(self, request):
        return render(request, 'index.html')

    def delFile(self, request):
        cookies = request.COOKIES
        user = ModelUtil.get_user(aj.load(cookies['user'])['email'])
        filename = request.data.get('filename')
        FileUtil.delete(user.email, filename)
        return Result.success()

    def newFile(self, request):
        cookies = request.COOKIES
        user = ModelUtil.get_user(aj.load(cookies['user'])['email'])
        filename = request.data.get('filename') + '.csv'
        flag, msg = FileUtil.create(user.email, filename)
        if flag:
            return Result.error(message=msg)
        return Result.success(message=msg)

    def dashboard(self, request):
        cookies = request.COOKIES
        user = ModelUtil.get_user(aj.load(cookies['user'])['email'])
        size = FileUtil.get_size(user.email)
        count = FileUtil.get_file_count(user.email)
        req = render(request, 'dashboard.html',
                     {
                         'email': user.email,
                         'size': round(size, 5),
                         'ram': round(float(user.ram) - float(size), 5),
                         'count': count,
                         'max_ram': user.ram,
                         'occupy': float(size) / float(user.ram) < 0.5
                     })
        req.set_cookie('user', user.to_json())
        return req

    def files(self, request):
        cookies = request.COOKIES
        user = ModelUtil.get_user(aj.load(cookies['user'])['email'])
        # file_name_list = FileUtil.get_file_list(user.email)
        infos = FileUtil.get_files_info(user.email)
        req = render(request, 'files.html', {'files': infos})
        req.set_cookie('user', user.to_json())
        return req
